<script setup lang="ts">
import { saveAs } from 'file-saver'
import VueQr from 'vue-qr/src/packages/vue-qr.vue'

import type { ColumnsType } from '@/components/common-table/types'
import FileList from '@/components/view-file/file-list.vue'
import useAppStore from '@/stores/modules/app'
import { getCurrency, isEmptyAll, timeFormat } from '@/utils/util'

export type PropsType = {
  column: ColumnsType
  optionsConfig?: {
    [key in ColumnsType['prop']]?: {
      label: string
      value: any
    }[] | undefined
  }
  showOverflowTooltip?: boolean
}

const { getImageUrl } = useAppStore()
const props = withDefaults(defineProps<PropsType>(), {
  column: () => ({
    label: '',
    prop: ''
  }),
  showOverflowTooltip: true
})

const tags = (row: any, column: ColumnsType) => {
  return column?.options?.find((v: any) => v.value == row[column.prop as string])
}

const emits = defineEmits(['switchChanged', 'edit'])

const qrcodeUrl = ref<any>({})

const downloadQrcode = async (row: any) => {
  const canvas = document.createElement('canvas').transferControlToOffscreen()
  canvas.width = 400
  canvas.height = 450

  const ctx = canvas.getContext('2d')
  ctx!.fillStyle = 'white'
  ctx!.fillRect(0, 0, 400, 450)

  const img = new Image()
  img.src = qrcodeUrl.value[row[props.column.prop]]

  await nextTick()

  ctx!.drawImage(img, 0, 0, 400, 400, 0, 0, 400, 400)

  // 绘制文字
  ctx!.font = '20px Arial'
  ctx!.textAlign = 'center'
  ctx!.fillStyle = '#000'
  ctx!.fillText(props.column.qrcodeConfig?.name(row) || '', 400 / 2, 450 - 20)
  const blob = await canvas.convertToBlob({
    type: 'image/png',
    quality: 0.9
  })
  saveAs(blob, `${props.column.qrcodeConfig?.name(row)}.png`)
  // downloadFile(qrcodeUrl.value, `${props.column.qrcodeConfig?.name(row)}.png`)
}
</script>

<template>
  <el-table-column
    :show-overflow-tooltip="showOverflowTooltip"
    :label="column.label"
    :prop="column.prop"
    :sortable="column.sortable"
    :min-width="column.minWidth"
    :header-align="column?.columns ? 'center' : ''"
    :fixed="column.fixed"
    :class-name="column.className"
  >
    <template #default="{ row }">
      <template v-if="column?.columns && column?.columns.length">
        <table-item v-for="(col, i) in column?.columns" :column="col" :key="i" />
      </template>
      <!--        链接-->
      <template v-else-if="column.type == 'link'">
        <el-link :href="row[column.prop]" type="primary" target="_blank">{{
          column.renderText?.(row, column) || '查看'
        }}</el-link>
      </template>
      <!--        自定义文本-->
      <template v-else-if="column.renderText">{{ column.renderText(row, column) }}</template>
      <!--        日期转换-->
      <template v-else-if="column.type == 'date'">{{
        row[column.prop] == 0 ? '--' : timeFormat(row[column.prop], column.fmt || 'yyyy-mm-dd')
      }}</template>
      <!--        wps日期转换-->
      <template v-else-if="column.type == 'wpsDate'">{{
        row[column.prop] == 0
          ? '--'
          : timeFormat((row[column.prop] - 25569) * 86400, column.fmt || 'yyyy-mm-dd')
      }}</template>
      <!--        金额千分符-->
      <template v-else-if="column.type == 'currency'">
          <div class="text-[20px] text-[#DC9B03] font-medium ff-BebasNeue">{{
                  column.renderCurrency
                      ? getCurrency(Number(column.renderCurrency?.(row,column)))
                      : getCurrency(Number(row[column.prop]))
              }}</div>
      </template>
      <!--        字段组合显示-->
      <template v-else-if="column.type == 'combination'">{{
        column.prop
          ?.split(',')
          ?.map((item: string) => row[item])
          .toString()
          ?.replaceAll(',', ' - ')
      }}</template>
      <!--        图片列表展示-->
      <template v-else-if="column.type == 'imgList'">
        <el-scrollbar v-if="row[column.prop]">
          <div>
            <el-image
              class="mr-[5px]"
              v-for="(item, i) in typeof row[column.prop] == 'string'
                ? row[column.prop]?.split(',')
                : row[column.prop]"
              :key="i"
              style="width: 50px; height: 50px"
              :src="getImageUrl(item)"
              :z-index="9999999"
              :preview-teleported="true"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="
                typeof row[column.prop] == 'string'
                  ? row[column.prop]?.split(',')?.map((v:any) => getImageUrl(v))
                  : row[column.prop]?.map((v:any) => getImageUrl(v))
              "
              :initial-index="i"
              fit="cover"
            />
          </div>
        </el-scrollbar>
        <div v-else>--</div>
      </template>
      <!--        文件列表展示-->
      <template v-else-if="column.type == 'fileList'">
        <el-scrollbar v-if="row[column.prop]">
          <file-list
            :files="
              typeof row[column.prop] == 'string' ? row[column.prop]?.split(',') : row[column.prop]
            "
          />
        </el-scrollbar>
        <div v-else>--</div>
      </template>
      <!--        图片列表展示-->
      <template v-else-if="column.type == 'imgListBase64'">
        <el-scrollbar v-if="row[column.prop]">
          <div>
            <el-image
              class="mr-[5px]"
              v-for="(item, i) in row[column.prop]"
              :key="i"
              style="width: 50px; height: 50px"
              :src="item"
              :z-index="9999999"
              :preview-teleported="true"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="row[column.prop]"
              :initial-index="i"
              fit="cover"
            />
          </div>
        </el-scrollbar>
        <div v-else>--</div>
      </template>
      <!--        图片列表展示-->
      <template v-else-if="column.type == 'video'">
        <div v-if="row[column.prop]">
          <el-image
            class="mr-[5px]"
            v-for="(item, i) in row[column.prop]?.split(',')"
            :key="i"
            style="width: 50px; height: 50px"
            :src="item"
            :z-index="9999999"
            :preview-teleported="true"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="row[column.prop]?.split(',')"
            :initial-index="i"
            fit="cover"
          />
        </div>
        <div v-else>--</div>
      </template>
      <!--        tag标签-->
      <template v-else-if="column.type == 'tags'">
        <div>
          <div v-if="tags(row, column)?.label">
            <el-tag
              :color="tags(row, column)?.bgColor"
              :style="{
                color: tags(row, column)?.color
              }"
              :type="tags(row, column)?.type || 'success'"
              >{{ tags(row, column)?.label }}</el-tag
            >
          </div>
          <div v-else>--</div>
        </div>
      </template>
      <!--        tag标签-->
      <template v-else-if="column.type == 'tagsList'">
        <div>
          <div class="overflow-x-auto" v-if="!isEmptyAll(row[column.prop])">
            <el-tag
              v-for="(item, i) in typeof row[column.prop] == 'string'
                ? row[column.prop]?.split(',')
                : row[column.prop]"
              :key="i"
              :type="column?.tagType || 'success'"
              >{{ item }}</el-tag
            >
          </div>
          <div v-else>--</div>
        </div>
      </template>
      <!--        tooltip  多行文本-->
      <template v-else-if="column.type == 'tooltip'">
        <div>
          <div :class="column.tooltipClass">
            {{ row[column.prop] }}
          </div>
        </div>
      </template>
      <!--        开关-->
      <template v-else-if="column.type == 'switch'">
        <div>
          <el-switch
            v-model="row[column.prop]"
            inline-prompt
            :active-text="column.switchConfig?.active.text"
            :inactive-text="column.switchConfig?.inactive.text"
            :active-value="column.switchConfig?.active.value"
            :inactive-value="column.switchConfig?.inactive.value"
            :active-color="column.switchConfig?.active.color"
            :inactive-color="column.switchConfig?.inactive.color"
            :disabled="column?.switchDisabled?.(row)"
            @change="(val:any) => emits('switchChanged', { column, row, val })"
          />
        </div>
      </template>
      <!--        二维码-->
      <template v-else-if="column.type == 'qrcode'">
        <div>
          <div v-if="row[column.prop]" class="w-[50px] h-[50px] relative qrcode">
            <div
              class="absolute download top-0 opacity-0 left-0 w-[100%] h-[100%] bg-[rgba(0,0,0,0.5)] flex flex-col items-center justify-center"
            >
              <div class="w-[100%] flex items-center justify-center" v-copy="row[column.prop]">
                <el-icon color="#fff" size="16"><DocumentCopy /></el-icon>
              </div>
              <div class="h-[5px]"></div>
              <div class="w-[100%] flex items-center justify-center" @click="downloadQrcode(row)">
                <el-icon color="#fff" size="16"><Download /></el-icon>
              </div>
            </div>
            <!--            <qrcode-vue ref="qrcodeRef" id="myCanvas" :value="row[column.prop]" :size="50" />-->
            <vue-qr
              :text="row[column.prop]"
              :size="400"
              :margin="0"
              logoBackgroundColor="rgba(0,0,0,0)"
              :logo-src="column.qrcodeConfig?.logo"
              :callback="(url:any) => qrcodeUrl[row[column.prop]] = url"
            />
          </div>
          <div v-else class="o-w">--</div>
        </div>
      </template>
      <!--        可编辑-->
      <template v-else-if="column.type == 'edit'">
        <div class="flex items-center">
          <div
            v-if="column?.editConfig?.type == 'select'"
            class="o-w"
            :style="column?.styleName?.(row)"
          >
            {{
              optionsConfig?.[column.prop]?.find((v: any) => v.value == row[column.prop])?.label ||
              '--'
            }}
          </div>
          <div v-else class="o-w">{{ row[column.prop] || '--' }}</div>
          <popover-input
            @confirm="(val:any) => emits('edit',{ column, row, val})"
            v-if="column?.editShow?.(row)"
            :value="row[column.prop] || '--'"
            :type="column?.editConfig?.type || 'textarea'"
            :options="optionsConfig?.[column.prop] || []"
            size="default"
            width="400px"
            :limit="200"
            show-limit
            teleported
          >
            <el-icon size="16" class="ml-[5px] cursor-pointer text-[#ccc] hover:text-[#666666]"
              ><Edit
            /></el-icon>
          </popover-input>
        </div>
      </template>
      <template v-else-if="column.type == 'noTooltip'">
        <div>{{ row[column.prop] || '--' }}</div>
      </template>
      <template v-else>
        <div class="o-w inline-flex">{{ row[column.prop] || '--' }}</div>
      </template>
    </template>
  </el-table-column>
</template>

<style scoped lang="scss">
.o-w {
  overflow: hidden; //超出的文本隐藏
  text-overflow: ellipsis; //溢出用省略号显示
  white-space: nowrap; //溢出不换行
}
.qrcode:hover {
  .download {
    opacity: 1;
    cursor: pointer;
    transition: all 0.2s;
  }
}
</style>
